package com.gxc.service.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Ip相关的工具类.
 *
 * @author 宫新程
 * @since 16-8-20 上午11:31
 */
public class IpUtil {

  private static final Logger logger = LoggerFactory.getLogger(IpUtil.class);

  /** 从request中获取客户端IP. 会考虑前面有反向代理的情况. */
  public static String getClientIp(HttpServletRequest request) {
    String clientIp;
    String ipFromNginx = request.getHeader("X-Forwarded-For");
    if (ipFromNginx != null && ipFromNginx.trim().length() > 0) {
      clientIp = ipFromNginx;
    } else {
      clientIp = request.getRemoteAddr();
    }

    if (clientIp == null || clientIp.trim().length() == 0) {
      clientIp = "unknown";
    } else if (clientIp.startsWith("0:0:0:0:0:")) {
      clientIp = "127.0.0.1";
    }
    return clientIp;
  }

  /**
   * 获取当前机器的hostname.
   *
   * @return hostname
   */
  public static String getHostName() {
    try {
      InetAddress ia = InetAddress.getLocalHost();
      return ia.getHostName();
    } catch (UnknownHostException ex) {
      logger.error("could not get hostname", ex);
      return "unknown";
    }
  }
}
